# coding=utf-8

from django.db import transaction
from django.contrib.auth import get_user_model
from rest_framework.views import APIView

from utils import response_ok
from utils.permission import IsAdministratorUser
from utils.custom_modelviewset import CustomModelViewSet
from apps.log.models import BizLog
from apps.admin import admin_log

from apps.account.filters import UserFilter
from .serializers import UserSerializer

User = get_user_model()

class UserViewSet(CustomModelViewSet):
    permission_classes = [IsAdministratorUser, ]
    queryset = User.objects.filter(is_active=True, type=User.ADMINSTRATOR)
    serializer_class = UserSerializer

    def filter_queryset(self, queryset):
        f = UserFilter(self.request.GET, queryset=queryset)
        return f.qs

    def perform_create(self, serializer):
        super(UserViewSet, self).perform_create(serializer)
        instance = serializer.instance
        validated_data = serializer.validated_data
        admin_log(self.request.user, BizLog.INSERT, u'添加用户[%s]，id=%d' % (instance.username, instance.id),validated_data)

    def perform_update(self, serializer):
        super(UserViewSet, self).perform_update(serializer)
        instance = serializer.instance
        validated_data = serializer.validated_data
        admin_log(self.request.user, BizLog.UPDATE, u'修改用户[%s]，id=%d' % (instance.username, instance.id), validated_data)

    def destroy(self, request, *args, **kwargs):
        with transaction.atomic():
            instance = self.get_object()
            instance.is_active = False
            instance.save()
            admin_log(self.request.user, BizLog.DELETE, u'禁用用户[%s]，id=%d' % (instance.username, instance.id))
        return response_ok()

class ChangePasswrodView(APIView):
    permission_classes = [IsAdministratorUser, ]

    def post(self, request):
        new_password = request.POST.get('new_password')
        confirm_password = request.POST.get('confirm_password')
        old_password = request.POST.get('old_password')

        with transaction.atomic():
            request.user.change_password(new_password, confirm_password, old_password)
            request.user.save()
        return response_ok()